package com.songlanyun.modules.rights.controller.admin;

import java.util.Arrays;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.annotation.RepeatSubmit;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.enums.RightsOrderConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.payrefund.entity.PayRefundOrder;
import com.songlanyun.modules.rabbitmq.mq.producer.SendOrderOrRightsOrderMsgService;
import com.songlanyun.modules.rights.entity.RightsOrderShipRecord;
import com.songlanyun.modules.rights.model.dto.ApplyOrderRightsDTO;
import com.songlanyun.modules.rights.model.dto.RightsInStockDTO;
import com.songlanyun.modules.rights.model.dto.RightsOrderOperateDTO;
import com.songlanyun.modules.user.controller.AbstractController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.songlanyun.modules.rights.entity.RightsOrder;
import com.songlanyun.modules.rights.service.RightsOrderService;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;


/**
 * 销售系统中的维权单（前期可能只做统一维权，不过这样不好）
 *
 * @author lubo
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 13:45:42
 */
@RestController
@RequestMapping("admin/rights")
public class RightsOrderAdminController extends AbstractController {
    @Autowired
    private RightsOrderService rightsOrderService;

    @Autowired
    private SendOrderOrRightsOrderMsgService sendOrderOrRightsOrderMsgService;

    @Autowired
    private OrderService orderService;

    /**
     * 商家查看维权订单列表
     */
    @RequestMapping("/page")
    //@RequiresPermissions("rights:salerightsorder:list")
    /**
     *  params参数说明
     *  rights_type 1仅退款,2退款退货
     *  order_code 订单编号
     *  mobile 会员手机号
     *  pay_refund_code 支付退款单编号
     *  refund_status （0待退款，1退款成功，2退款失败）
     *  operate_status 维权订单操作状态（0申请，1同意，2买家已发货，3商家已收到退货商品,4商家发起退款支付，5已支付退款,6拒绝，7自动关闭,8主动撤消
     *  page 当前第几页（默认第一页）
     *  limit 每页多少条 （默认每页10条）
     */
    public R page(@RequestParam Map<String, Object> params) {
        if (isShop()) {
            params.put("shop_id", getShopId(true));
        }
        PageUtils page = rightsOrderService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 商家查查看维权订单详情
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R info(@PathVariable("id") Long id) {
        RightsOrder rightsOrder;
        if (isShop()) {
            rightsOrder = rightsOrderService.loadByShopIdAndId(getShopId(true), id, false);
        } else {
            rightsOrder = rightsOrderService.loadById(id, false);
        }

        if (rightsOrder == null) {
            return R.ok().put("data", null);
        }
        rightsOrder.loadRightsChildOrders();
        rightsOrder.loadRightsOrderOperateRecords();
        return R.ok().put("data", rightsOrder);
    }


    /**
     * 商家发起自动退款 (发起普通订单退款)
     */
    @SysLog("商家发起自动退款")
    @PostMapping("/launch/{orderId}")
    public R shopLaunchRefund(@PathVariable("orderId") Long orderId) {
        //订单是否已经封单，如果封单无法发起退款
        if (orderService.getById(orderId).getEnd()){
            throw new RRException("订单已完成，无法发起退款");
        }
        PayRefundOrder payRefundOrder = rightsOrderService.shopLaunchRefund(getShopId(true), orderId);
        if (payRefundOrder != null && RightsOrderConstant.RightsRefundStatus.SUCCESS.equals(payRefundOrder.getRightsRefundStatus())) {
            sendOrderOrRightsOrderMsgService.rightsRefundSuccessSendMsg(payRefundOrder);
        }
        return R.ok();
    }

    /**
     * 商家发起自动退款 (发起服务订单退款)
     */
    @SysLog("商家发起服务订单自动退款")
    @PostMapping("/launch/service")
    public R shopLaunchServiceRefund(@RequestBody ApplyOrderRightsDTO dto) {
        PayRefundOrder payRefundOrder = rightsOrderService.shopServiceOrderRefund(getShopId(true), dto);
        if (payRefundOrder != null && RightsOrderConstant.RightsRefundStatus.SUCCESS.equals(payRefundOrder.getRightsRefundStatus())) {
            sendOrderOrRightsOrderMsgService.rightsRefundSuccessSendMsg(payRefundOrder);
        }
        return R.ok();
    }


    /**
     * 商家退款
     */
    @SysLog("商家退款")
    @PostMapping("/refund")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R refund(@RequestBody RightsOrderOperateDTO dto) {
        PayRefundOrder payRefundOrder = rightsOrderService.refund(getShopId(true), dto);
        // 维权退款成功发送微信小程序消息
        if (payRefundOrder != null && RightsOrderConstant.RightsRefundStatus.SUCCESS.equals(payRefundOrder.getRightsRefundStatus())) {
            // 发送微信小程序消息
            sendOrderOrRightsOrderMsgService.rightsRefundSuccessSendMsg(payRefundOrder);

            // 修改主订单信息
            Long rightsOrderId = dto.getRightsOrderId();
            RightsOrder one = rightsOrderService.getOne(new LambdaQueryWrapper<RightsOrder>()
                    .eq(RightsOrder::getId, rightsOrderId));
            Long orderId = one.getOrderId();
            Order order = orderService.getById(orderId);
            order.setTransactionStatus(OrderConstant.TransactionStatus.CLOSE);

            return R.ok("退款成功");
        } else {
            return R.ok("退款进行中");
        }
    }


    /**
     * 商家同意维权
     */
    @SysLog("商家同意维权")
    @PostMapping("/agree")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R agree(@RequestBody RightsOrderOperateDTO dto) {
        RightsOrder rightsOrder = rightsOrderService.agree(getShopId(true), dto);

        sendOrderOrRightsOrderMsgService.rightsAgreeSendMsg(rightsOrder);
        return R.ok().put("data", rightsOrder);
    }

    /**
     * 商家拒绝维权
     */
    @SysLog("商家拒绝维权")
    @PostMapping("/refuse")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R refuse(@RequestBody RightsOrderOperateDTO dto) {
        RightsOrder rightsOrder = rightsOrderService.refuse(getShopId(true), dto);

        sendOrderOrRightsOrderMsgService.rightsRefuseSendMsg(rightsOrder);
        return R.ok().put("data", rightsOrder);
    }

    /**
     * 商家取消维权
     * @param rightsId
     * @return
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/cancel/{userId}/{rightsId}")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R cancel(@PathVariable("userId") Long userId, @PathVariable("rightsId") Long rightsId){
        RightsOrder rightsOrder = rightsOrderService.cancel(userId,rightsId);
        return R.ok().put("data",rightsOrder);
    }

    /**
     * 商家收货
     */
    @SysLog("商家收货")
    @PostMapping("/receipt")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R receipt(@RequestBody RightsOrderOperateDTO dto) {
        RightsOrder rightsOrder = rightsOrderService.receipt(getShopId(true), dto);

        sendOrderOrRightsOrderMsgService.rightReceiptSendMsg(rightsOrder);
        return R.ok();
    }


    /**
     * 商家手动入库
     */
    @SysLog("商家手动入库")
    @PostMapping("/instock")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R inStock(@RequestBody RightsInStockDTO dto) {
        RightsOrder rightsOrder = rightsOrderService.inStock(getShopId(true), dto);
        return R.ok();
    }


    /**
     * 物流跟踪
     */
    @GetMapping("/express/select/{rightsId}")
    //@RequiresPermissions("ship:saleorderpackage:save")
    public R expressSelect(@PathVariable("rightsId") Long rightsId) {
        RightsOrderShipRecord rightsOrderShipRecord = rightsOrderService.expressSelect(rightsId);

        if (rightsOrderShipRecord == null) {
            return R.ok().put("data", null);
        }

        if (StringUtils.isBlank(rightsOrderShipRecord.getQueryResult())) {
            return R.ok().put("data", null);
        }

        JSONObject jsonObject = JSONObject.parseObject(rightsOrderShipRecord.getQueryResult());
        return R.ok().put("data", jsonObject);
    }

    /**
     * 快钱退款
     */
    @PostMapping("/kq/refund")
    public R kqRefund() {
        return rightsOrderService.kqRefund();
    }


}
